package com.platform.api.bzproject.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.platform.api.bzproject.model.*;
import com.platform.api.bzproject.service.*;
import com.platform.api.common.component.ImageCompressComponent;
import com.platform.common.core.Constant;
import com.platform.common.core.Result;
import com.platform.common.core.oss.AttachFileService;
import com.platform.common.core.oss.OssProcess;
import com.platform.common.core.oss.VideoFirstFrame;
import com.platform.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author guoyunfei on 2021/9/23 21:58
 * @className DouyinWallpaperController
 * @description TODO 抖音壁纸API
 * @Version 1.0
 * 源码联系微信：2549789059
 */
@Api(tags = "抖音壁纸信息")
@RestController
@RequestMapping("{appid}/platform")
public class BzAllWallpaperController {

    @Autowired
    private BzClassificationService bzClassificationService;

    @Autowired
    private BzBannerService bzBannerService;

    @Autowired
    private BzNoticeService bzNoticeService;


    @Autowired
    private BzBaseInfoService bzBaseInfoService;

    @Autowired
    private BzAllWallpaperService bzAllWallpaperService;

    @Autowired
    private IBzTalentService iBzTalentService;

    @Autowired
    private AttachFileService attachFileService;

    @Autowired
    private BzFavoriteService bzFavoriteService;

    @Autowired
    private IWallpaperTagsService iWallpaperTagsService;

    @Autowired
    private ImageCompressComponent imageCompressComponent;



    @ApiOperation(value = "壁纸接口列表", notes="壁纸接口列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码，默认1", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "条数，默认12", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "order", value = "排序字段0浏览数1点赞数2收藏数", required = false, dataType = "String"),
            @ApiImplicitParam(name = "openid", value = "用户微信openid", required = true, dataType = "String"),
            @ApiImplicitParam(name = "appid", value = "小程序appid", required = true, dataType = "String"),
    })
    @GetMapping("/wallpaper")
    private Result selectAllWallpaper(BzAllWallpaper wallpaper, Integer pageNum, Integer pageSize, Integer order, @PathVariable String appid){

        if(null == pageNum){
            pageNum = 1;
        }
        if(null == pageSize){
            pageSize = 18;
        }
        wallpaper.setStatus(2);
        wallpaper.setAppid(null);
        //没有分类时查询小程序默认的类型
        if(null == wallpaper.getClassId()){
            String classType = "1";
            //查询小程序默认的类型
            BzBaseInfo baseInfo = bzBaseInfoService.selectOne(appid);
            if(null != baseInfo){
                if(baseInfo.getHomeType() != 0){
                    classType = String.valueOf(baseInfo.getHomeType());
                }
            }
            wallpaper.setClassType(classType);
        }

        //排序
        String orderBy = bzAllWallpaperService.getOrderBy(order);
        PageInfo<BzAllWallpaper> pageInfo = bzAllWallpaperService.selectAllWallpaper(wallpaper, pageNum, pageSize,orderBy);
        List<BzAllWallpaper> list = pageInfo.getList();
        pageInfo.setList(list);
        return Result.success(pageInfo);
    }

    @GetMapping("/selectMyWallpaper")
    private Result selectMyWallpaper(BzAllWallpaper wallpaper, Integer pageNum, Integer pageSize, Integer order){

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure("获取用户信息失败");
        }

        wallpaper.setOpenid(userId);
        if(null == pageNum){
            pageNum = 1;
        }
        if(null == pageSize){
            pageSize = 18;
        }
        //wallpaper.setAppid(appid);
        //排序
        String orderBy = bzAllWallpaperService.getOrderBy(order);
        PageInfo<BzAllWallpaper> pageInfo = bzAllWallpaperService.selectAllWallpaper(wallpaper, pageNum, pageSize,orderBy);
        List<BzAllWallpaper> list = pageInfo.getList();
        pageInfo.setList(list);
        return Result.success(pageInfo);
    }


    /**
     * 查询图片详情
     * @param id 壁纸id
     * @return
     */
    @GetMapping("/data.json")
    public Result get(Integer id,@PathVariable String appid,String userId){

        if(null == id){
            return Result.failure("获取参数失败");
        }

        Map<String,Object> map = new HashMap<>(6);
        BzAllWallpaper bzWallpaper = bzAllWallpaperService.getWallpaperById(id);
        map.put("bzWallpaper",bzWallpaper);
        BzBaseInfo info = bzBaseInfoService.selectOne(appid);
        //工具栏
        map.put("switch_comment",info.getIsTools());
        map.put("showAd",info.getShowAd());
        //小程序名称
        map.put("title",info.getAppName());
        //每日下载次数
        map.put("adCount",info.getAdCount());
        map.put("downCount",info.getDownCount());
        map.put("putongDown",info.getPutongDown());
        //关闭手机类型收益
        map.put("closeProfit",info.getCloseProfit());

        if(null != bzWallpaper){
            //TODO 获取壁纸所属用户信息
            BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", bzWallpaper.getOpenid()).last("limit 1"));
            map.put("talent",talent);

            //增加浏览数
            BzAllWallpaper w = bzAllWallpaperService.getById(id);
            w.setBrowseCount(null == w.getBrowseCount() ? 1 : w.getBrowseCount() + 1);
            bzAllWallpaperService.updateById(w);
        }


        //增加我的浏览记录
        if(StringUtils.isNotBlank(userId)){

            BzFavorite favorite = bzFavoriteService.getOne(
                    new QueryWrapper<BzFavorite>().eq("openid", userId)
                    .eq("wallpaper_Id",id)
                    .eq("type",3).last("limit 1")
            );
            if(null == favorite){
                favorite = new BzFavorite();
                favorite.setCreateTime(new Date());
                favorite.setWallpaperId(id);
                //favorite.setAppid(appid);
                favorite.setType(3);
                favorite.setOpenid(userId);
                //bzFavoriteService.save(favorite);
            }

            //获取是否点赞和收藏
            favorite = bzFavoriteService.getOne(
                    new QueryWrapper<BzFavorite>().eq("openid", userId)
                            .eq("wallpaper_Id",id)
                            .eq("type",1)
            );
            map.put("post_favorite",null != favorite ? 1 : 0);
            favorite = bzFavoriteService.getOne(
                    new QueryWrapper<BzFavorite>().eq("openid", userId)
                            .eq("wallpaper_Id",id)
                            .eq("type",2)
            );
            map.put("post_like",null != favorite ? 1 : 0);
        }

        return Result.success(map);
    }

    @ApiOperation(value = "首页信息加载", notes="首页信息加载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appid", value = "小程序appid", required = true, dataType = "String"),
    })
    @GetMapping("index")
    public Result index(@PathVariable String appid){
        Map<String,Object> map = new HashMap<>(6);
        // TODO 全局配置信息


        // TODO 获取随机6条达人信息
        List<Map<String, Object>> talents = iBzTalentService.selectLimitBzTalent();
        map.put("talents",talents);
        try {
            // TODO banner
            BzBanner banner = new BzBanner();
            banner.setEnable(1);
            banner.setAppid(appid);
            List<BzBanner> bzBannerList = bzBannerService.bannerList(banner);

            map.put("banners",bzBannerList);
            // TODO banner end


            // TODO 分类
            BzClassification classification = new BzClassification();
            classification.setEnable(1);
            //多账号时开放
            //classification.setAppid(appid);
            List<BzClassification> classifications = bzClassificationService.selectList(classification);
            map.put("classifications",classifications);

            // TODO 消息公告
            BzNotice notice = new BzNotice();
            notice.setEnable(1);
            notice.setType(1);
            List<BzNotice> notices = bzNoticeService.selectList(notice);
            map.put("notices",notices);
            BzBaseInfo info = bzBaseInfoService.selectOne(appid);
            if(null != info){
                //设置小程序logo
                map.put("logo",null == info.getAppLogo() ? null : info.getAppLogo());
                map.put("title",null == info.getAppName() ? null : info.getAppName());
            }


            return Result.success(map);
        }catch (Exception e){
            return Result.failure("服务器错误");
        }
    }

    /**
     * 获取壁纸数量
     * @return
     */
    @GetMapping("getMyCount")
    public Result getMyCount(){
        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure("获取用户信息失败");
        }

        int count = bzAllWallpaperService.count(new QueryWrapper<BzAllWallpaper>().eq("openid", userId));
        return Result.success(count);
    }




    /**
     * 获取壁纸上一张 下一张
     */
    @GetMapping("upAndDownData")
    public Result upAndDownData(@PathVariable String appid, Integer id,String createTime,String flag,String openid){
        if(null == id){
            return Result.failure("获取参数失败");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("flag",flag);
        //map.put("appid",appid);
        BzAllWallpaper wallpaper = bzAllWallpaperService.upAndDownData(map);
        if(null == wallpaper){
            return Result.failure("没有了哦");
        }

        Map<String,Object> resultMap = new HashMap<>(6);
        resultMap.put("bzWallpaper",wallpaper);
        //查询用户是否收藏此 查询类型为2的
        if(StringUtils.isNotBlank(openid)){
            BzFavorite collection = new BzFavorite();
            collection.setOpenid(openid);
            collection.setWallpaperId(wallpaper.getId());
            //collection.setAppid(appid);
            collection.setType(1);
            resultMap.put("post_favorite", bzFavoriteService.selectCount(collection) > 0 ? 1 : 0);
            collection.setType(2);
            resultMap.put("post_like", bzFavoriteService.selectCount(collection)  > 0 ? 1 : 0);
        }
        BzBaseInfo info = bzBaseInfoService.selectOne(appid);
        resultMap.put("switch_comment",info.getIsTools());
        resultMap.put("title",info.getAppName());
        return Result.success(resultMap);
    }


    /**
     * 查询图片详情
     * @param id 壁纸id
     * @return
     */
    @GetMapping("/getDataDetail")
    public Result getDataDetail(Integer id){

        if(null == id){
            return Result.failure("获取参数失败");
        }

        Map<String,Object> map = new HashMap<>(6);
        BzAllWallpaper bzWallpaper = bzAllWallpaperService.getWallpaperById(id);
        if(null == bzWallpaper){
            return Result.failure("获取数据失败");
        }
        map.put("bzWallpaper",bzWallpaper);
        return Result.success(map);
    }


    /**
     * @return
     */
    @GetMapping("/deleteImage/{id}")
    public Result deleteImage(@PathVariable Integer id){

        if(null == id){
            return Result.failure("删除失败");
        }

        //bzAllWallpaperService.removeById(id);
        BzAllWallpaper allWallpaper = bzAllWallpaperService.getById(id);
        allWallpaper.setIsDelete(0);
        allWallpaper.setTopping(0);
        bzAllWallpaperService.updateById(allWallpaper);

        return Result.success();
    }

    /**
     * @return
     */
    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody Integer[] ids){

        if(null == ids){
            return Result.failure("请选择要删除的数据");
        }

        Collection<BzAllWallpaper> entityList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            BzAllWallpaper allWallpaper = new BzAllWallpaper();
            allWallpaper.setIsDelete(0);
            allWallpaper.setId(ids[i]);
            allWallpaper.setTopping(0);
            entityList.add(allWallpaper);
        }

        bzAllWallpaperService.updateBatchById(entityList);
        return Result.success();
    }

    /**
     * @return
     */
    @PostMapping("/setClassData/{twoClassId}")
    public Result setClassData(@RequestBody Integer[] ids,@PathVariable Integer twoClassId){

        if(null == ids){
            return Result.failure("请选择要设置的数据");
        }

        Collection<BzAllWallpaper> entityList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            BzAllWallpaper allWallpaper = new BzAllWallpaper();
            allWallpaper.setId(ids[i]);
            allWallpaper.setTwoClassId(twoClassId);
            entityList.add(allWallpaper);
        }

        bzAllWallpaperService.updateBatchById(entityList);
        return Result.success();
    }

    @PostMapping("saveWallpaper")
    public Result saveWallpaper(@RequestParam("file") MultipartFile file,BzAllWallpaper bzAllWallpaper) throws IOException, NoSuchAlgorithmException, KeyManagementException {

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            if(StringUtils.isNotBlank(userId)){
                bzAllWallpaper.setOpenid(userId);
            }
        }catch (Exception e){
            return Result.failure("获取用户信息失败");
        }

        if(StringUtils.isEmpty(bzAllWallpaper.getOpenid())){
            return Result.failure("请先登录在进行操作");
        }

        BzTalent bzTalent = iBzTalentService.getOne(
                new QueryWrapper<BzTalent>().eq("userid", bzAllWallpaper.getOpenid())
                        .eq("status",2)
                        .last("limit 1"));
        if(null == bzTalent){
            return Result.failure("您不是创作者,请先申请");
        }

        file = imageCompressComponent.imageCompres(file);
        String filename = attachFileService.uploadFile(file, null);

        String domain = attachFileService.getDomain();

        String fileUrl = domain + "/" +filename;

        //原始图片地址
        String oriFileUrl = fileUrl;

        //检查是否是图片
        if("2".equals(bzAllWallpaper.getClassType())){
            //获取视频首帧参数
            String firstFrame = VideoFirstFrame.getFirstFrame(attachFileService.getOssType());
            fileUrl = fileUrl + firstFrame;
            //设置低画质图片
            bzAllWallpaper.setLowImageQuality(oriFileUrl + VideoFirstFrame.getFirstFrameNoAd(attachFileService.getOssType()));

        }else{

            //添加压缩参数
            String compress = OssProcess.getCompress(attachFileService.getOssType());
            fileUrl = fileUrl + compress;
            //设置低画质图片
            bzAllWallpaper.setLowImageQuality(oriFileUrl + OssProcess.getCompressNoAd(attachFileService.getOssType()));

        }

        bzAllWallpaper.setImage(oriFileUrl);

        bzAllWallpaper.setThumbnail(fileUrl);

        bzAllWallpaper.setIsDelete(1);
        bzAllWallpaper.setCreateTime(new Date());
        bzAllWallpaper.setTime(new Date());

        bzAllWallpaper.setImgSize(file.getSize());

        if(3 != bzAllWallpaper.getStatus()){
            bzAllWallpaper.setStatus(1);
        }
        bzAllWallpaperService.save(bzAllWallpaper);

        //添加数据到标签表
        Collection<WallpaperTags> tagsList = new ArrayList<>();

        String[] split = bzAllWallpaper.getTagsIds().split(",");
        for (int i = 0; i < split.length; i++) {
            WallpaperTags wt = new WallpaperTags();
            wt.setTid(Long.valueOf(split[i]));
            wt.setWid(bzAllWallpaper.getId());
            tagsList.add(wt);
        }

        iWallpaperTagsService.saveBatch(tagsList);

        return Result.success();
    }


    @GetMapping("updateAllUserData")
    public Result updateAllUserData(){
        int allUserData = bzAllWallpaperService.updateAllUserData();
        return Result.success("同步成功,同步条数："+allUserData);
    }


}
